const systemOutbund = require('./sqlStatement/systemOutbund.js');
const baseFn = require('../../public/base.js');


/**
 * 销售出库系统获取基本信息接口
 */
const getOrder = async (ctx, next) => {
    try {
        const body = ctx.query;
        const result = await systemOutbund.sendOrderData(body);
        const list = result.recordset.map(key => {
            const rq = JSON.stringify(key.RQ)
                .split('T')[0]
                .split('"')[1];
            const yjs = key.YJS || 0;
            const sk = key.YJS || 0;
            const zl = sk - yjs;
            return {
                RQ: rq,
                DWBM: key.DWBM,
                DWMC: key.DWMC,
                JSFSBM: key.JSFSBM,
                JSFSMC: key.JSFSMC,
                ZSL: key.ZSL,
                ZJS: key.ZJS,
                ZSS: key.ZSS,
                ZSE: key.ZSE,
                ZHJ: key.ZHJ,
                ZJE: key.ZJE,
                DH: key.DH,
                ID: key.ID,
                STATE: key.SFMZ,
                YJS: yjs,
                SK: sk,
                ZL: zl,
                BZ: key.BZ,
                DZ: key.DZ,
                _checked: false
            };
        });

        ctx.body = list;
    } catch (err) {
        ctx.body = err;
    }
}


/**
 * 销售出库系统获取详细信息接口
 */
const getDetail = async (ctx, next) => {
    const id = ctx.query.id;
    const MX = await systemOutbund.sendDetail(id);
    ctx.body = MX.recordset;
}

/**
 * 销售出库系统获取最新一条数据接口
 */
const getStream = async (ctx, next) => {
    const MX = await systemOutbund.sendStream();
    ctx.body = MX.recordset;
}

/**
 * 销售出库系统更新备注接口
 */

const setRemark = async (ctx, next) => {
    const body = ctx.request.body;
    const BZ = body.data;
    const ID = body.id;
    const MX = await systemOutbund.setRemark(BZ, ID);
    ctx.body = MX.recordset;
}

/**
 * 销售出库系统提交审核接口
 */

const setReview = async (ctx, next) => {
    let newID = '';
    try {
        let time = new Date();
        let month = time.getMonth() + 1;
        let day = time.getDate();
        let year = time.getFullYear().toString();
        year = year.substring(year.length - 2);
        if (day < 10) {
            day = '0' + day;
        } else {
            day = day.toString();
        }
        if (month < 10) {
            month = '0' + month;
        } else {
            month = month.toString();
        }
        let newId = year + month + day;
        const newTime = baseFn.getNowFormatDate();
        const body = ctx.request.body;
        const abs =
            time.getFullYear() +
            1 +
            '-' +
            (time.getMonth() + 1) +
            '-' +
            time.getDate() +
            ' ' +
            '00:00:00.000';

        let arr = [];
        let arr1 = [];
        let orderArr = [];
        for (let i = 0; i < body.list.length; i++) {
            const e = body.list[i];
            let status = false;
            let status1 = false;
            console.log('zhix1');
            for (let y = 0; y < e.length; y++) {
                const ks = e[y];
                const count = await systemOutbund.reviewsCount(
                    ks.YPBM,
                    ks.SCPH,
                    ks.CKBM,
                    ks.YXQZ,
                    ks.SCRQ,
                    ks.CBJJ
                );

                const count1 = await systemOutbund.reviewsOrder(ks.ID);
                const count2 = await systemOutbund.isWrite(ks.ID);
                console.log('zhix2', count2);
                const kcsl = count.recordset[0].KCSL;
                const SH = count1.recordset[0].SH;
                if (SH === 'F' || count2.recordset.length >= 1) {
                    status1 = true;
                } else if (ks.SL > kcsl) {
                    status = true;
                }
            }
            if (status) {
                arr.push({
                    id: e[0].ID
                });
            } else if (status1) {
                arr1.push({
                    id: e[0].ID
                });
            } else {
                console.log('id', e[0].ID);
                let zcb = 0;
                newID = '';
                e.forEach(key => {
                    zcb += key.CBJJ * key.SL;
                });
                const MX = await systemOutbund.sendStream();
                const stream = MX.recordset[0].ID;
                const streamId = stream.substring(stream.length - 4);
                const oldTime = stream.substring(0, 6);
                let newTream = 0;
                if (Number(newId) === Number(oldTime)) {
                    newTream = Number(streamId) + 1;

                    if (newTream < 10) {
                        newTream = `000${newTream}`;
                    } else if (newTream >= 10 && newTream < 100) {
                        newTream = `00${newTream}`;
                    } else if (newTream >= 100 && newTream < 1000) {
                        newTream = `0${newTream}`;
                    } else {
                        newTream = `${newTream}`;
                    }
                } else {
                    newTream = '0001';
                }
                newID = newId + body.value.BMBM + body.value.JBRBM + '12' + newTream;
                console.log('newID', newID);
                for (let event = 0; event < body.lists.length; event++) {
                    const j = body.lists[event];
                    if (j.ID === e[0].ID) {
                        await systemOutbund.updateZB(newID, newTime, j, body, abs, zcb);

                        await systemOutbund.updateJS(newID, j, body);
                    }
                }

                for (let w = 0; w < e.length; w++) {
                    const we = e[w];
                    const nb = baseFn.setTime(w, we.YXQZ);
                    const shijian = `${time.getMinutes().toString()}${
            time.getSeconds().toString() >= 10
              ? time.getSeconds().toString()
              : '0' + time.getSeconds().toString()
          }${nb}`;

                    const queryCount = await systemOutbund.reviewsCount(
                        we.YPBM,
                        we.SCPH,
                        we.CKBM,
                        we.YXQZ,
                        we.SCRQ,
                        we.CBJJ
                    );
                    const CXSL = queryCount.recordset[0].KCSL;

                    await systemOutbund.updateKC(CXSL, we);

                    await systemOutbund.updateMX(we, newID, shijian, nb, day, abs);
                }

                orderArr.push({
                    time: newTime,
                    newId: newID,
                    id: e[0].ID
                });
            }
        }
        const listData = {
            arr: arr,
            arr1: arr1,
            orderArr: orderArr
        };

        ctx.body = listData;
    } catch (err) {
        console.log('err-----', err);
        // const result = await systemOutbund.getZB(newID)
        // if (result.recordset[0].ID) {
        //   await sql.query `DELETE FROM XSD_ZB WHERE ID = ${newID}`
        //   await sql.query `DELETE FROM XSD_JS WHERE ID = ${newID}`
        //     await sql.query `DELETE FROM XSD_MX WHERE ID = ${newID}`
        // }

        ctx.body = {
            err: err.originalError.info.message
        };
    }
}

module.exports = {
    'GET /getOrder': getOrder,
    'GET /getDetail': getDetail,
    'GET /getStream': getStream,
    'PATCH /setRemark': setRemark,
    'POST /setReview': setReview
}